package com.moyoutian.leetcode;


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 19. 删除链表的倒数第 N 个结点
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * <p>
 * 进阶：你能尝试使用一趟扫描实现吗？
 */


public class Demo19 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1, new ListNode(2));
        ListNode listNode = removeNthFromEnd(listNode1, 2);
        System.out.println("Demo19.main");
    }

    public static ListNode removeNthFromEnd2(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        List<ListNode> list = new LinkedList<>();
        ListNode tempNode = head;
        while (tempNode != null) {
            list.add(tempNode);
            tempNode = tempNode.next;
        }
        int index = list.size() - n;
        //头结点
        if (index == 0) {
            return head.next;
        } else if (index > 0) {
            //删除结点前面的结点
            ListNode remNodeLastOne = list.get(index - 1);
            if (remNodeLastOne.next != null) {
                remNodeLastOne.next = remNodeLastOne.next.next;
            }
        } else {
            throw new RuntimeException("非法的输入");
        }
        return head;
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        int count = getCount(head);
        int index = count - n;
        //头结点
        if (index == 0) {
            return head.next;
        } else if (index > 0) {
            ListNode tempNode = head;
            index--;
            while (tempNode != null && index > 0) {
                index--;
                tempNode = tempNode.next;
            }
            tempNode.next = tempNode.next.next;
        } else {
            throw new RuntimeException("非法的输入");
        }
        return head;
    }

    public static int getCount(ListNode head) {
        int count = 0;
        while (head != null) {
            count++;
            head = head.next;
        }
        return count;
    }


}
